package chatdialogservicelogic

import (
	"context"

	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *pb.ChatDialogListReq) (*pb.ChatDialogListResp, error) {
	dialogs, err := l.svcCtx.ChatDialogModel.FindMany(l.ctx, in.AssistantId, in.UserId)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialog List: failed by Assistant Id: %s, User Id: %d", in.AssistantId, in.UserId)
	}
	respDialogs := make([]*pb.ChatDialog, 0, len(dialogs))
	for _, dia := range dialogs {
		respDialogs = append(respDialogs, &pb.ChatDialog{
			Id:           dia.ID.Hex(),
			UpdateAt:     dia.UpdateAt.Unix(),
			CreateAt:     dia.CreateAt.Unix(),
			Name:         dia.Name,
			LastActiveAt: dia.LastActiveAt.Unix(),
			AssistantId:  dia.AssistantId.Hex(),
			UserId:       dia.UserId,
		})
	}

	return &pb.ChatDialogListResp{
		Dialogs: respDialogs,
	}, nil
}
